package cn.iocoder.yudao.framework.business.comment.service;

import cn.iocoder.yudao.framework.business.basic.dao.query.CoreQueryWrapper;
import cn.iocoder.yudao.framework.business.basic.service.impl.BaseService;
import cn.iocoder.yudao.framework.business.comment.pojo.form.CommentQueryDTO;
import cn.iocoder.yudao.framework.business.comment.pojo.form.CommentReplyForm;
import cn.iocoder.yudao.framework.business.comment.pojo.form.CommentSaveDTO;
import cn.iocoder.yudao.framework.business.comment.pojo.po.CommentEntity;
import cn.iocoder.yudao.framework.business.comment.pojo.vo.AdminCommentVO;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import jakarta.annotation.Nonnull;

/**
 * 评论 Service 实现类，由子类继承，子类标注 @{@link org.springframework.stereotype.Service}
 *
 * @author 山野羡民
 */
//@org.springframework.stereotype.Service
public abstract class AdminCommentBaseService<DO extends CommentEntity, RESP extends AdminCommentVO, SAVE extends CommentSaveDTO, QUERY extends CommentQueryDTO> extends BaseService<DO, RESP, QUERY> implements AdminCommentService<RESP, SAVE, QUERY> {

    @Nonnull
    @Override
    protected CoreQueryWrapper<DO> buildQueryWrapper(QUERY param) {
        CoreQueryWrapper<DO> wrapper = super.buildQueryWrapper(param);
        wrapper.eqIfPresent("parent_id", param.getParentId());
        wrapper.eqIfPresent("grandpa_id", param.getGrandpaId());
        return wrapper;
    }

    /**
     * 创建评论
     *
     * @param userId 用户编号
     * @param reqVO  创建请求
     * @return 返回评论编号
     */
    @Override
    public Long createComment(Long userId, SAVE reqVO) {
        // 校验评论
        validateBeforeCreate(userId, reqVO);
        DO comment = BeanUtils.toBean(reqVO, resolveEntityClass());
        comment.setUserId(userId);
        comment.setTargetUserId(comment.getUserId());
        // 插入
        getInjectedMapper().insert(comment);
        return comment.getId();
    }

    protected abstract void validateBeforeCreate(Long userId, SAVE reqVO);

    /**
     * 回复评论
     *
     * @param userId 用户编号
     * @param reqVO  回复请求
     */
    @Override
    public Long replyComment(Long userId, CommentReplyForm reqVO) {
        // 校验存在
        DO commentDO = validateExists(reqVO.getCommentId());
        // 校验评论
        validateBeforeReply(userId, commentDO);
        DO comment = BeanUtils.toBean(commentDO, resolveEntityClass());
        comment.setParentId(commentDO.getId());
        comment.setGrandpaId(commentDO.getParentId());
        comment.setUserId(userId);
        comment.setTargetUserId(commentDO.getUserId());
        // 插入
        getInjectedMapper().insert(comment);
        return comment.getId();
    }

    protected abstract void validateBeforeReply(Long userId, DO bean);

}
